package com.bey.bow.service.content;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bey.bow.entity.ContentDetail;
import com.bey.bow.repository.ContentDetailDao;

@Component
@Transactional(readOnly = true)
public class ContentDetailService {

	private ContentDetailDao contentDetailDao;

	@Transactional(readOnly = false)
	public void saveContentDetail(ContentDetail entity) {
		contentDetailDao.save(entity);
	}

	public ContentDetail getContentDetail(Long id) {
		return contentDetailDao.findOne(id);
	}

	@Transactional(readOnly = false)
	public void deleteContentDetail(Long id) {
		contentDetailDao.delete(id);
	}

	public Page<ContentDetail> getContentDetails(int pageNumber, int pageSize,
			String sortType) {

		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize,
				sortType);
		return contentDetailDao.findAll(pageRequest);

	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize,
			String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("date".equals(sortType)) {
			sort = new Sort(Direction.DESC, "contentDetailDate");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	@Autowired
	public void setContentDetailDao(ContentDetailDao contentDetailDao) {
		this.contentDetailDao = contentDetailDao;
	}

}
